# -*- coding: utf-8 -*- 
# @Time : 2021/10/23 23:36 
# @Author : Dong 
# @File : user_infor.py
from flask_restful import Resource,marshal_with,fields

from ihome import constants, db
from ihome.utils import marshal_json
from ihome.utils.commons import login_status, data_base_error
from flask import g, request, jsonify, current_app, session

from ihome.utils.image_storage import storage
from ihome.utils.response_code import RET, error_map

class UserInfor(Resource):

    @login_status
    @marshal_with(marshal_json.data_fields('users_fields'))
    def get(self):
        return constants.return_template_json(RET.OK,error_map.get(RET.OK),g.user)

    @login_status
    @data_base_error
    def patch(self):
        req_name = request.json.get('name')
        if req_name is None:
            return jsonify(constants.return_template_json(RET.PARAMERR, error_map.get(RET.PARAMERR)))

        # 保存用户昵称 并同时判断name是否重复（利用数据库的唯一索引）
        g.user.name = req_name
        db.session.commit()

        session['name'] = req_name
        return jsonify(constants.return_template_json(RET.OK, error_map.get(RET.OK), {'user_name': req_name}))

class User_real_name(Resource):
    @login_status
    @data_base_error
    @marshal_with(marshal_json.data_fields('users_fields'))
    def get(self):
        return constants.return_template_json(RET.OK,error_map.get(RET.OK),g.user)

    @login_status
    @data_base_error
    def post(self):
        real_name = request.json.get('real_name')
        id_card = request.json.get('id_card')

        if not all([real_name,id_card]):
            return jsonify(constants.return_template_json(RET.PARAMERR, error_map.get(RET.PARAMERR)))

        # 介入第三放的实名查询
        # 目前还没有

        g.user.id_card = id_card
        g.user.real_name = real_name
        db.session.commit()
        return jsonify(constants.return_template_json(RET.OK, error_map.get(RET.OK)))


